﻿using DevExpress.XtraReports.Web.WebDocumentViewer;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ReportDesignerServer.Models;
using System.Net.Http.Headers;

namespace ReportDesignerServer.Controllers
{
    /// <summary>
    /// ArchiveController
    /// </summary>
    [ApiExplorerSettings(IgnoreApi = true)]
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class ArchiveController : ControllerBase
    {
        readonly IWebDocumentViewerReportResolver reportResolver;
        readonly IConfiguration configuration;

        public ArchiveController(IWebDocumentViewerReportResolver reportResolver, IConfiguration configuration)
        {
            this.reportResolver = reportResolver;
            this.configuration = configuration;
        }

        /// <summary>
        /// 归档
        /// </summary>
        /// <param name="archive">归档实例</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<string> SaveReport([FromBody] ArchiveEntity archive)
        {
            try
            {
                var report = reportResolver.Resolve(archive.reportName + "|" + archive.id);
                var fileName = $"{archive.id}-{archive.reportName}.pdf";
                var txtFileName = $"{archive.id}-{archive.reportName}.txt";
                await report.ExportToPdfAsync(fileName);//生成归档pdf文件
                await report.ExportToTextAsync(txtFileName);//生成归档txt内容文件
                if (System.IO.File.Exists(fileName) && System.IO.File.Exists(txtFileName))
                {
                    var uploadUrl = configuration["goFastDfs:uploadUrl"];
                    var bytes = System.IO.File.ReadAllBytes(fileName);
                    //上次归档文件到fastdfs 返回结果
                    var result = PostImport(uploadUrl, bytes, fileName);
                    var fastDfs = JsonConvert.DeserializeObject<GoFastDfs>(result);
                    if (fastDfs != null && fastDfs.status == "ok")
                    {
                        //读取归档文件内容
                        var content = System.IO.File.ReadAllText(txtFileName, System.Text.Encoding.GetEncoding("gb2312"));
                        var solr = new SolrEntity()
                        {
                            id = archive.id,
                            content = content,
                            fileName = fileName,
                            filePath = fastDfs?.data?.path,
                            title = archive.title,
                            author = archive.author
                        };
                        var solrResult = addFiles(solr);
                        //删除文件
                        System.IO.File.Delete(fileName);
                        System.IO.File.Delete(txtFileName);
                        return solrResult;
                    }
                    else
                    {
                        return "err:upload fail";
                    }
                }
                else
                {
                    return "err:archive fail";
                }
            }
            catch (Exception ex)
            {
                return "err:" + ex.Message;
            }
        }

        /// <summary>
        /// 取消归档
        /// </summary>
        /// <param name="archive">归档实例</param>
        /// <returns></returns>
        [HttpGet]
        public string CancelReport(string id)
        {
            try
            {
                var result = removeFile(id);
                return result;
            }
            catch (Exception ex)
            {
                return "err:" + ex.Message;
            }
        }
        /// <summary>
        /// 向webapi发送请求执行导入操作
        /// </summary>
        /// <param name="token">身份验证token</param>
        /// <param name="reauestUrl">api请求完整路径</param>
        /// <param name="bytes">文件byte[]</param>
        /// <param name="fileName">文件名称</param>
        /// <returns>{"data": {"domain": "http://192.168.103.165:9080", "md5": "0b22002005b65e6f6cc39a48e21ff90a", "mtime": 1692857909, "path": "/group1/default/20230824/14/18/7/Report1.txt", "retcode": 0, "retmsg": "", "scene": "default", "scenes": "default", "size": 8, "src": "/group1/default/20230824/14/18/7/Report1.txt", "url": "http://192.168.103.165:9080/group1/default/20230824/14/18/7/Report1.txt?name=Report1.txt&download=1"}, "message": "", "status": "ok"}</returns>
        private string PostImport(string reauestUrl, byte[] bytes, string fileName)
        {
            HttpClient httpClient = new HttpClient();
            ByteArrayContent fileContent = new ByteArrayContent(bytes);
            fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "file", FileName = fileName };
            MultipartFormDataContent content = new MultipartFormDataContent();
            content.Add(fileContent);
            content.Add(new StringContent("default"), "scene");
            content.Add(new StringContent("json2"), "output");
            content.Add(new StringContent("archive"), "path");
            var result = httpClient.PostAsync(reauestUrl, content);
            return result.Result.Content.ReadAsStringAsync().Result;
        }

        /// <summary>
        /// 向solr引擎添加文件
        /// </summary>
        /// <param name="solr">文件实例</param>
        /// <returns></returns>
        private string addFiles(SolrEntity solr)
        {
            HttpClient httpClient = new HttpClient();
            var addFilesUrl = configuration["solr:addFiles"];
            if (string.IsNullOrEmpty(addFilesUrl))
            {
                return "solr not enable";
            }
            else
            {
                var result = httpClient.PostAsJsonAsync(addFilesUrl, solr);
                return result.Result.Content.ReadAsStringAsync().Result;
            }

        }

        /// <summary>
        /// 向solr引擎删除文件
        /// </summary>
        /// <param name="solr">文件实例</param>
        /// <returns></returns>
        private string removeFile(string id)
        {
            HttpClient httpClient = new HttpClient();
            var removeFileUrl = configuration["solr:removeFile"];
            if (string.IsNullOrEmpty(removeFileUrl))
            {
                return "solr not enable";
            }
            else
            {
                var result = httpClient.GetAsync(removeFileUrl + id);
                return result.Result.Content.ReadAsStringAsync().Result;
            }

        }
    }
}
